package com.hp.rccpp.spr.rt.crmsimulator.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShellExecutorServlet extends HttpServlet {

	private static final String PATH = "path";
	private static final String FILE_NOT_FOUND_ERROR = "The file does not exist: ";
	private static final long serialVersionUID = -7174697121474290540L;

	// private static final Logger log =
	// LoggerFactory.getLogger(ShellExecutorServlet.class);

	@Override
	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {

		doPost(arg0, arg1);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String shellScriptPath = null;

		// use the shell script path if it specified in HTML Form.
		shellScriptPath = request.getParameter(PATH);

		// if not, use the value configured in web.xml.
		if (shellScriptPath == null || "".equals(shellScriptPath)) {
			shellScriptPath = getServletConfig().getInitParameter(PATH);
		}

		shellScriptPath = URLDecoder.decode(shellScriptPath, "UTF-8");

		OutputStream out = response.getOutputStream();

		File f = new File(shellScriptPath);

		if (!f.exists()) {
			out.write((FILE_NOT_FOUND_ERROR + shellScriptPath).getBytes());
			return;
		}

		try {
			Process process = Runtime.getRuntime().exec(shellScriptPath);
//			BufferedReader reader = new BufferedReader(new InputStreamReader(
//					process.getInputStream()));
//			String msg = null;
//			while ((msg = reader.readLine()) != null) {
//				out.write((encodeHTML(msg) + "<br/>").getBytes());
//			}
		} catch (IOException exception) {
			out.write("Job finished with error!".getBytes());
		}
		out.write("Job finished successfully!".getBytes());
		response.flushBuffer();
	}

	private static String encodeHTML(String s) {
		StringBuffer out = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c > 127 || c == '"' || c == '<' || c == '>') {
				out.append("&#" + (int) c + ";");
			} else {
				out.append(c);
			}
		}
		return out.toString();
	}

}
